<script setup lang="ts">
import { key, FormItem } from "./type";
import { inject, onMounted, ref } from "vue";
import mitter from "../../utils/mitter";
import Schema from "async-validator";

defineOptions({ name: "ElFormItem" });

interface IProps {
  prop?: string;
  label?: string;
}

const props = withDefaults(defineProps<IProps>(), {
  label: "",
  prop: "",
});

const formData = inject(key);
const errMessage = ref("");

const validator = () => {
  if (!formData?.rules) {
    return Promise.resolve({ res: true });
  }

  const rules = formData.rules[props.prop];
  const value = formData.model[props.prop];

  const schema = new Schema({
    [props.prop]: rules,
  });

  return schema.validate({ [props.prop]: value }, (err) => {
    if (err) {
      errMessage.value = err[0].message || "校验错误";
    } else {
      errMessage.value = "";
    }
  });
};

const o: FormItem = {
  validator,
};

defineExpose(o);

onMounted(() => {
  if (props.prop) {
    mitter.emit("addFormItem", o);
    mitter.on("validate", () => {
      validator();
    });
  }
});
</script>

<template>
  <div>
    <div v-if="props.label" class="label">{{ props.label }}</div>
    <slot></slot>
    <div v-if="errMessage" class="err-message">{{ errMessage }}</div>
  </div>
</template>
